import React, { RefObject, useEffect } from 'react';
import ReactModal from 'react-modal';

import { ReactComponent as ChevronLeft } from '@/assets/images/auth/ChevronLeft.svg';
import { ReactComponent as CrossIcon } from '@/assets/images/shared/close-modal.svg';
import { ModalContext } from '@/shared/context/ModalContext';
import { useScrollLock } from '@/shared/lib/hooks';
import cn from 'classnames';
import { useWindowSize } from 'usehooks-ts';

import cs from './Modal.module.scss';

interface Props extends ReactModal.Props {
  onCloseClick?: () => void;
  className?: string;
  isMobile?: boolean;
  zIndex?: number;
  crossWithShadow?: boolean;
  withGoBack?: boolean;
  handleGoBack?: () => void;
  noOverlay?: boolean;
  containerClassName?: string;
  innerRef?: RefObject<HTMLDivElement>;
}
// touchAction: 'none'
export const Modal = ({
  data,
  isOpen = false,
  zIndex,
  withGoBack = false,
  onCloseClick,
  handleGoBack,
  crossWithShadow = false,
  children,
  containerClassName,
  className,
  noOverlay = false,
  isMobile,
  style,
  innerRef,
  ...props
}: Props) => {
  const { lock, unlock } = useScrollLock();
  const { closeModal, id } = React.useContext(ModalContext);
  const { width } = useWindowSize();
  useEffect(() => {
    if (isMobile && width > 1023) {
      onCloseClick?.();
    }
  }, [width]);
  useEffect(() => {
    isOpen ? lock() : unlock();
  }, [isOpen]);

  return (
    <ReactModal
      ariaHideApp={false}
      className={cn(cs.modal, className)}
      isOpen={isOpen}
      onAfterClose={() => closeModal}
      onRequestClose={onCloseClick || closeModal}
      overlayClassName={!noOverlay ? cs.overlay : cs.noOverlay}
      shouldCloseOnEsc={props.shouldCloseOnEsc}
      shouldCloseOnOverlayClick={false}
      style={{ overlay: { touchAction: 'auto', zIndex } }}
      {...props}
    >
      <div className={cn(cs.container, containerClassName)} ref={innerRef}>
        {withGoBack && (
          <div className={cs.chevron_left} onClick={handleGoBack}>
            <ChevronLeft />
          </div>
        )}
        <button
          className={cn(cs.cross, crossWithShadow && cs.cross_shadow)}
          data-testid="button-close_modal"
          onClick={onCloseClick || closeModal}
          type="button"
        >
          <CrossIcon />
        </button>
        {children}
      </div>
    </ReactModal>
  );
};
